import Vue from 'vue'
import Vuex, {
  createLogger
} from 'vuex'
import request from '@/utils/request'
import axios from 'axios'


Vue.use(Vuex)

export default new Vuex.Store({
  // state中存放的就是全局共享的数据
  state: {
    // 商品分类列表数据
    FoodData: [],
    //商铺列表数据
    ShopData: [],
    //搜索餐厅的数据
    SearchData: [],
    //配送方法的数据
    DistriButionData: [],
    //商家属性的数据
    attributeData: [],
    //餐馆详情
    DetailsData: [],
    //食品详情列表数据
    shipinData: [],
    //评价分数数据
    ScoreData: null,
    //评价分类数据
    classification: [],
    //评价信息
    RatingsData: [],
    //购物车总价格
    price: 0,
    // 购物车总数据
    values: 0,
    //分类左侧的索引
    activeIndex: 0,
    //购物车的状态
    show: false,
    //下拉菜单栏的购物车信息
    MenuData: [],
    //购物车菜单栏的状态
    showCh: false,
    // 食品详情的数据
    FoodDetailsData: [],
    // 购物车请求返回的数据
    SettlemenData: [],
    // 订单备注信息
    remarkData: [],
    //需要选择的发票抬头信息
    InvoiceText: null,
    //登录成功的用户信息
    UserData: {},
    //搜索到的地址数据
    SearchAddressData: [],
    // 点击存储的地址对象
    AddressDataObj: {},
    // 用户ID获取到的地址
    ShippingAddress: [],
    //可用红包数据
    envelopeData: [],
    // 我的优惠个数
    envelopeNumber: 0,
    // 过期红包
    hbHistoryData: [],
    // 服务中心
    freshmanData: [],
    // 服务中心的具体说明数组
    specify: [],
    // 具体说明的标题和索引
    obj: {},
    // 服务中心的具体说明数据
    specifyDataAdd: {},
    // 服务中心的具体说明图片资源
    imgpathData: [],
    imageData: {},
    // 订单列表数据
    OrdersData: [],
    // 点击列表列表的索引
    indexData: 0,
    // 口味备注
    textAddData: '',
    // 所有备注信息
    ReturnDataList: '',
    // 选择地址的索相
    addressIndex: {
      index: 0,
      id: 31797
    },
    // 热门城市
    cityData: [],
    // 定位城市数据
    positioningCity: {},
    // 所有城市
    AllCity: [],
    cityTitleData: '',
    messageData: '',
  },
  // Getters用于对Store中的数据进行加工处理形成新的数据
  getters: {
    FoodDate(state) {
      return state.FoodData.slice(8)
    },
    FoodDat(state) {
      return state.FoodData.slice(0, 8)
    },
    items(state) {
      //将食品左侧标题内容提取出来，将name改为text,官方规定的
      return state.shipinData.map(({
        name
      }) => ({
        text: name
      }))
    },

  },
  // 不要在mutations函数中，执行异步操作
  // 只有mutations中定义的函数，才有权利修改state中的数据
  mutations: {
    //将食品分类列表数据存入 state中的FoodData
    FoodList(state, res) {
      state.FoodData = res

    },
    // 将经续度的地址存入
    geohashList(state, res) {
      state.cityTitleData = res.name
    },
    //将商铺列表数据存入 state中的ShopData
    ShopList(state, ShopData) {
      state.ShopData = ShopData

    },
    //将搜索的数据存入state中
    SearchList(state, SearchData) {
      state.SearchData = SearchData
      state.messageData = SearchData.message
    },
    //清除搜索的数据
    removeData(state) {
      return state.SearchData = []
    },
    //将再次筛选商品列表数据存入ShopData2
    ShopList3(state, res) {
      state.ShopData = res
    },
    //商家分类数据列表
    ShopList4(state, res) {
      state.ShopData = res
    },
    //将配送方式数据存入state中
    DistriButionList(state, res) {
      state.DistriButionData = res
    },
    //将商家属性数据存入state中
    attributeList(state, res) {
      state.attributeData = res
    },
    //将再次筛选商品列表数据存入ShopData2
    supportList(state, res) {
      state.ShopData = res
    },
    //餐馆详情数据存入state
    DetailsList(state, res) {
      state.DetailsData = res
    },
    //食品数据存入state
    shipinList(state, req) {
      state.shipinData = req
    },
    //评论分数
    ScoreList(state, res) {
      state.ScoreData = res
    },
    //评价分类
    classificationList(state, res) {
      state.classification = res
    },
    //评价信息
    RatingsList(state, res) {
      for (let i = 0; i < res.length; i++) {
        state.RatingsData.push(res[i])
      }
    },
    //点击加号计算食品价格
    add(state, obj) {
      state.price += obj.price
      //相示对象类型的索引
      const i = state.MenuData.map((item) => item.id).indexOf(obj.id)
      //如果数量大于1就删除相同对象
      for (let j = 0; j < state.MenuData.length; j++) {
        if (state.MenuData[j].id === obj.id) {
          state.MenuData.splice(i, 1)
        }
      }
      // state.MenuData.push(obj)
      state.MenuData.push(obj)
      state.values += 1

    },
    //点击减号计算食品价格
    add1(state, obj) {
      state.price -= obj.price
      state.values -= 1
      const i = state.MenuData.map((item) => item.id).indexOf(obj.id)
      //如果数量大于1就删除相同对象
      for (let j = 0; j < state.MenuData.length; j++) {
        if (state.MenuData[j].id === obj.id) {
          state.MenuData[i].quantity -= 1
        }
        if (state.MenuData[j].quantity === 0) {
          state.MenuData = state.MenuData.filter(item => item.id !== obj.id)
        }
      }
      if (state.values === 0) {
        state.showCh = false
      }

    },
    showxiu1(state, show) {
      state.show = show
    },
    showxiu2(state, show) {
      state.show = show
    },
    //购物车菜单栏状态变化 
    shoppingCart(state) {
      if (state.values !== 0 && state.showCh === false) {
        state.showCh = true
      } else {
        state.showCh = false
      }
    },
    //购物车请求需要的数据存入
    FoodAdd(state, obj) {
      state.FoodDetailsData = obj
    },
    // 购物车请求返回的数据存入
    SettlemenList(state, res) {
      state.SettlemenData = res
    },
    // 点击返回按钮清空购物车菜单栏数据MenuData和values
    empty(state) {
      state.MenuData = []
      state.values = 0
      state.price = 0
    },
    // 将订单备注数据存入
    remarkinioList(state, res) {
      state.remarkData = res
    },
    //将需要选择发票信息存入
    InvoiceList(state, text) {
      state.InvoiceText = text
    },
    // 将登录成功的用户信息存入
    userList(state, res) {
      state.UserData = res
    },
    // 修改用户名
    UserCheck(state, values) {
      state.UserData.username = values
    },
    // 将搜索到的地址存入
    SearchAddressList(state, res) {
      state.SearchAddressData = res
    },
    // 点击搜索到的地址存入
    chooseAddressList(state, item) {
      state.AddressDataObj = item
    },
    // 通过用户ID获取到的收货地址存入
    ShippingAddress(state, res) {
      state.ShippingAddress = res
    },
    // 可用红包数据
    envelope(state, req) {
      state.envelopeData = req
      state.envelopeNumber = req.length
    },
    // 过期红包数据存入
    hbHistoryAdd(state, res) {
      state.hbHistoryData = res

    },
    // 服务中心数据存入
    freshmanList(state, res) {
      // state.freshmanData = res.split('### ')
      const obj = [{
          text: res.supervipCaption
        },
        {
          text: res.signCaption
        },
        {
          text: res.rankCaption
        },
        {
          text: res.pointtextCaption
        },
        {
          text: res.phototutorialCaption
        },
        {
          text: res.paymentCaption
        },
        {
          text: res.otherCaption
        },
        {
          text: res.ontimeCaption
        },
        {
          text: res.memberTimesCaption
        },
        {
          text: res.memberCaption
        },
        {
          text: res.hongbaoCaption
        },
        {
          text: res.freshmanCaption
        },
        {
          text: res.forgotCaption
        },
        {
          text: res.discountCaption
        },
        {
          text: res.disclaimerCaption
        },
        {
          text: res.couponCaption
        },
        {
          text: res.businessCaption
        },
        {
          text: res.balanceCaption
        },
        {
          text: res.awesomeRestaurantCaption
        },
        {
          text: res.anonymousBuyCaption
        },
        {
          text: res.activityCaption
        }
      ]
      const specifyData = [{
          text: res.supervipContent
        },
        {
          text: res.signContent
        },
        {
          text: res.rankContent
        },
        {
          text: res.pointtextContent
        },
        {
          text: res.phototutorialContent
        },
        {
          text: res.paymentContent
        },
        {
          text: res.otherContent
        },
        {
          text: res.ontimeContent
        },
        {
          text: res.memberTimesContent
        },
        {
          text: res.memberContent
        },
        {
          text: res.hongbaoContent
        },
        {
          text: res.freshmanContent
        },
        {
          text: res.forgotContent
        },
        {
          text: res.discountContent
        },
        {
          text: res.disclaimerContent
        },
        {
          text: res.couponContent
        },
        {
          text: res.businessContent
        },
        {
          text: res.balanceContent
        },
        {
          text: res.awesomeRestaurantContent
        },
        {
          text: res.anonymousBuyContent
        },
        {
          text: res.activityContent
        },
      ]
      state.freshmanData = obj
      state.specify = specifyData
    },
    // 将点击服务中心具体说明的标题和索引存入
    questionDetailAdd(state, obj) {
      state.obj = obj
      const imgpath = [{
          url: 'http://fuss10.elemecdn.com/5/de/5efc9ee81ceba1ae835b0c2298ba9jpeg.jpeg'
        },
        {
          url: 'http://fuss10.elemecdn.com/8/89/4920bc3a0a34c0d26a4460ce03157jpeg.jpeg'
        },
        {
          url: 'http://fuss10.elemecdn.com/8/89/4920bc3a0a34c0d26a4460ce03157jpeg.jpeg'
        },
        {
          url: 'http://fuss10.elemecdn.com/c/3b/958696046787bb467708c8d9a5171jpeg.jpeg'
        },
        {
          url: 'http://fuss10.elemecdn.com/2/d3/d31b1f81eb853c6042b9c172a514bjpeg.jpeg'
        },
        {
          url: 'http://fuss10.elemecdn.com/a/fe/b9716e028917fd81f6c5a99242b6fjpeg.jpeg'
        },
      ]
      const image = [{
        url: 'https://fuss10.elemecdn.com/f/08/bb0bcfc2a10e26524633e38ea47f6jpeg.jpeg'
      }]
      // 当进入有图片页面时就将图片存入
      if (obj.index === 4) {
        state.imgpathData = imgpath
      }
      // 当进入有图片页面时就将图片存入
      if (obj.index === 19) {
        state.imageData = image
      }
      state.specifyDataAdd = state.specify[obj.index]
      state.specifyDataAdd = state.specifyDataAdd.text.split('### ')
    },
    freshmanList1(state, res) {
      const specifyData = [{
        text: res.hongbaoContent
      }, ]
      state.specify = specifyData
      state.specifyDataAdd = state.specify[0]
      state.specifyDataAdd = state.specifyDataAdd.text.split('### ')
    },
    freshmanList2(state, res) {
      const specifyData = [{
        text: res.memberTimesContent
      }, ]
      state.specify = specifyData
      state.specifyDataAdd = state.specify[0]
      state.specifyDataAdd = state.specifyDataAdd.text.split('### ')
    },
    // 清空图片数据
    AddGOback(state) {
      state.imgpathData = []
      state.imageData = []
    },
    // 将订单列表数据存入
    OrdersList(state, res) {
      state.OrdersData = res
    },
    // 将点击订单列表的索引存入
    Getindex(state, index) {
      state.indexData = index
    },
    // 将快速备注信息存入
    textAdd(state, text) {
      state.textAddData = text
    },
    // 将所有的备注信息存入
    ReturnData(state, text) {
      state.ReturnDataList = text
    },
    // 选择收货地址的索引
    ChangeIndex(state, obj) {
      state.addressIndex = obj
    },
    // 定位城市 热门城市 所有城市列表存入
    cityList(state, res) {
      state.positioningCity = res

    },
    cityList1(state, obj) {
      state.cityData = obj.res
      state.AllCity = obj.req
    },
    // 如果sessionStorage里没有用户ID就清除用户
    removeUser(state) {
      state.UserData = {}
      state.envelopeNumber = 0
    }
  },
  // 如果通过异步操作变更数据，必须通过 ActionS,而不能使用Mutations
  // 注意： 在Actions 中不能直接修改 state中的数据，要通过 mutations修改
  actions: {
    //请求食品分类列表
    async getFoodList(data) {
      const {
        data: res
      } = await request.get('v2/index_entry')
      data.commit('FoodList', res)
    },
    // 请求根据经纬度获取的具体地址
    async getohash(data, geohash) {
      const {
        data: res
      } = await request.get(`v2/pois/${geohash}`)
      data.commit('geohashList', res)
    },
    //请求商铺列表数据
    async getShopsList(data, geohashJS) {
      const {
        data: res
      } = await request.get(`shopping/restaurants?latitude=${geohashJS[0]}&longitude=${geohashJS[1]}`)
      data.commit('ShopList', res)
    },

    //搜索
    async Searchrest(data, value) {
      const geohash = window.sessionStorage.getItem('geohash')
      const {
        data: res
      } = await request.get(`v4/restaurants?geohash=${geohash}&keyword=${value}`)
      data.commit('SearchList', res)
    },
    //请求商铺筛选列表数据2
    async checkList(data, value) {
      const geohashJS = window.sessionStorage.getItem('geohash').split(',')
      const {
        data: res
      } = await request.get(`shopping/restaurants?latitude=${geohashJS[0]}&longitude=${geohashJS[1]}`, {
        params: {
          order_by: value,
        }
      })
      data.commit('ShopList3', res)
    },
    //请求分类选择的数据
    async checkList2(data, ClassID) {
      const geohashJS = window.sessionStorage.getItem('geohash').split(',')
      const {
        data: res
      } = await request.get(`shopping/restaurants?latitude=${geohashJS[0]}&longitude=${geohashJS[1]}`, {
        params: {
          restaurant_category_id: ClassID.category_id,
          restaurant_category_ids: Array.of(ClassID.category_ids),
        }
      })
      data.commit('ShopList4', res)
    },
    //请求配送方式的数据
    async GETdistribution(data) {
      const geohashJS = window.sessionStorage.getItem('geohash').split(',')
      const {
        data: res
      } = await request.get(`shopping/v1/restaurants/delivery_modes?latitude=${geohashJS[0]}&longitude=${geohashJS[1]}`)
      data.commit('DistriButionList', res)
    },
    //请求商家属性的数据
    async GETattribute(data) {
      const geohashJS = window.sessionStorage.getItem('geohash').split(',')
      const {
        data: res
      } = await request.get(`shopping/v1/restaurants/activity_attributes?latitude=${geohashJS[0]}&longitude=${geohashJS[1]}`)
      data.commit('attributeList', res)
    },
    //请求商家筛选商家属性特权数据
    async supportID(data, obj) {
      const geohashJS = window.sessionStorage.getItem('geohash').split(',')
      const {
        data: res
      } = await request.get(`shopping/restaurants?latitude=${geohashJS[0]}&longitude=${geohashJS[1]}`, {
        params: {
          delivery_mode: Array.of(obj.Bution),
          support_ids: obj.indexID
        }
      })
      data.commit('supportList', res)
    },

    async getDetails(data, shopid) {
      //请求餐馆详情数据
      const {
        data: res
      } = await request.get(`shopping/restaurant/${shopid}`)
      data.commit('DetailsList', res)

    },
    async getshipin(data, shopid) {
      //食品列表数据
      const {
        data: req
      } = await request.get(`shopping/v2/menu?restaurant_id=${shopid}`)
      data.commit('shipinList', req)
    },
    // 请求获取评价分数数据
    async getScore(data, id) {
      const {
        data: res
      } = await request.get(`ugc/v2/restaurants/${id}/ratings/scores`)
      data.commit('ScoreList', res)
    },
    //请求评价分类
    async classification(data, id) {
      const {
        data: res
      } = await request.get(`ugc/v2/restaurants/${id}/ratings/tags`)
      data.commit('classificationList', res)
    },
    //请求评价信息
    async getRatings(data, obj) {
      const {
        data: res
      } = await request.get(`ugc/v2/restaurants/${obj.restaurant_id}/ratings?offset=${obj.offset}&limit=${obj.limit}&tag_name=${obj.tag_name}`)
      data.commit('RatingsList', res)
    },
    // 请求购物车数据
    async Settlemen(data, obj) {
      const geohash = window.sessionStorage.getItem('geohash')
      const {
        data: res
      } = await request.post(`v1/carts/checkout`, {
        restaurant_id: window.sessionStorage.getItem('shopid'),
        geohash,
        entities: [obj],
      })
      data.commit('SettlemenList', res)
    },
    // 请求订单备注信息
    async remarkList(data, id) {
      const {
        data: res
      } = await request.get(`v1/carts/${id}/remarks`)
      console.log(res);
      data.commit('remarkinioList', res)
    },
    // 获取用户信息
    async getUser(data) {
      const {
        data: res
      } = await request.get(`v1/user`)
      data.commit('userList', res)
    },
    async getEnvelope(data, user_id) {
      // 获取可用红包
      const {
        data: req
      } = await request.get(`promotion/v2/users/${user_id}/hongbaos?limit=20&offset=0`)
      data.commit('envelope', req)
    },
    // 搜索地址
    async SearchAddress(data, obj) {
      const {
        data: res
      } = await request.get(`https://elm.cangdu.org/v1/pois?city_id=${obj.id}&keyword=${obj.value}&type=search`)
      data.commit('SearchAddressList', res)
    },
    // 获取收货地址
    async getAddress(data, id) {
      const {
        data: res
      } = await request.get(`v1/users/${id}/addresses`)
      data.commit('ShippingAddress', res)
    },
    // 发起过期红包请求
    async hbHistoryList(data, id) {
      const {
        data: res
      } = await request.get(`promotion/v2/users/${id}/expired_hongbaos?limit=20&offset=0`)
      data.commit('hbHistoryAdd', res)
    },
    // 发起服务中心请求
    async freshmanContent(data) {
      const {
        data: res
      } = await request.get(`v3/profile/explain`)
      data.commit('freshmanList', res)
    },
    async freshmanContent1(data) {
      const {
        data: res
      } = await request.get(`v3/profile/explain`)
      data.commit('freshmanList1', res)
    },
    async freshmanContent2(data) {
      const {
        data: res
      } = await request.get(`v3/profile/explain`)
      data.commit('freshmanList2', res)
    },
    // 发起订单列表数据请求
    async GetOrders(data, id) {
      const {
        data: res
      } = await request.get(`bos/v2/users/${id}/orders?limit=10&offset=0`)
      data.commit('OrdersList', res)
    },
    // 发起获取城高列表
    async Getcity(data) {
      // 定位
      const {
        data: res
      } = await axios.get(`https://elm.cangdu.org/v1/cities?type=guess`)
      data.commit('cityList', res)
    },
    async Getcity1(data) {
      // 热门城市
      const {
        data: res
      } = await request.get(`v1/cities?type=hot`)
      // 全部城市
      const {
        data: req
      } = await request.get(`v1/cities?type=group`)
      const obj = {
        res,
        req
      }
      data.commit('cityList1', obj)
    }
  }
})